package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ReportMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.util.StringUtil;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    @Autowired
    private ReportMapper reportMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private WorkspaceService workspaceService;
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {

        List<LocalDate> dateList =new ArrayList<>();
        dateList.add(begin);
        while(!begin.equals( end)){
            begin= begin.plusDays(1);
            dateList.add(begin);
        }

        List<Double> list = new ArrayList<>();
        for(LocalDate date:dateList){
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Double v = reportMapper.sumByMap(beginTime, endTime);
            v = v==null ? 0.0 : v;
            list.add(v);
        }
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .turnoverList(StringUtils.join(list,","))
                .build();
    }

    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList =new ArrayList<>();
        dateList.add(begin);
        while(!begin.equals( end)){
            begin= begin.plusDays(1);
            dateList.add(begin);
        }
        List<Integer> totalUserList = new ArrayList<>();
        List<Integer> newUserList = new ArrayList<>();
        for(LocalDate date:dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Integer totalUser = userMapper.countByDate(endTime);
            totalUser= totalUser==null?0:totalUser;
            totalUserList.add(totalUser);
            Integer newUser = userMapper.newcountByDate(beginTime,endTime);
            newUser= newUser==null?0:newUser;
            newUserList.add(newUser);
        }
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .build();

    }

    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList =new ArrayList<>();
        dateList.add(begin);
        while(!begin.equals( end)){
            begin= begin.plusDays(1);
            dateList.add(begin);
        }
        List<Integer> validOrderCount=new ArrayList<>();
        List<Integer> totalOrderCount=new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Integer totalCount = orderMapper.totalCountByDate(beginTime, endTime);
            totalCount = totalCount==null?0:totalCount;
            totalOrderCount.add(totalCount);
            Integer validCount = orderMapper.validCountByDate(beginTime, endTime);
            validCount = validCount==null?0:validCount;
            validOrderCount.add(validCount);
        }
        Integer i = 0;
        Integer j = 0;
        for(int d = 0; d< dateList.size(); d++) {
            i += validOrderCount.get(d);
            j += totalOrderCount.get(d);
        }
        Double orderCompletionRate = 0.0;
        if(j==0) {
            orderCompletionRate = 0.0;
        }else{
            orderCompletionRate = i.doubleValue() / j.doubleValue();
        }
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .orderCountList(StringUtils.join(totalOrderCount,","))
                .validOrderCountList(StringUtils.join(validOrderCount,","))
                .validOrderCount(i)
                .totalOrderCount(j)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        // 查询top10
        List<GoodsSalesDTO> salesTop10 = reportMapper.getSalesTop10(begin, end);
        //select od.name, count(oc.name)*od.number as number
        // from order_detail od join orders o on o.id = od.order_id
        // where o.order_time between begin and end group by od.name order by number desc limit 10
        String nameList = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.joining(","));
        String numberList = salesTop10.stream().map(GoodsSalesDTO::getNumber).map(x -> x + "").collect(Collectors.joining(","));
        // List< String> nameList = new ArrayList<>();
        // List< String> numberList = new ArrayList<>();
        // for(GoodsSalesDTO dto : salesTop10){
        //     nameList.add(dto.getName());
        //     numberList.add(dto.getNumber() + "");
        // }
        return SalesTop10ReportVO.builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }

    @Override
    public void exportBusinessData(HttpServletResponse response) {
        LocalDate date = LocalDate.now();
        LocalDate begin = date.minusDays(30);
        LocalDate end = date.minusDays(1);
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(begin,LocalTime.MIN),LocalDateTime.of(end,LocalTime.MAX));
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            XSSFWorkbook excel = new XSSFWorkbook(in);
            XSSFSheet sheet = excel.getSheet("Sheet1");
            sheet.getRow(1).getCell(1).setCellValue("时间: "+begin+"至"+end);
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());
            for (int i = 0; i <30 ; i++) {
                LocalDate date1 = begin.plusDays(i);
                BusinessDataVO businessData1 = workspaceService.getBusinessData(LocalDateTime.of(date1,LocalTime.MIN),LocalDateTime.of(date1,LocalTime.MAX));
                row=sheet.getRow(7+i);
                row.getCell(1).setCellValue(date1.toString());
                row.getCell(2).setCellValue(businessData1.getTurnover());
                row.getCell(3).setCellValue(businessData1.getValidOrderCount());
                row.getCell(4).setCellValue(businessData1.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData1.getUnitPrice());
                row.getCell(6).setCellValue(businessData1.getNewUsers());

            }
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            // 关闭流
            out.close();
            excel.close();

        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
